<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="/css/sat-carconfig.css" rel="stylesheet">
    <title>汽车选配系统</title>
</head>
<body>
<div class="container">
    <div class="main-content">
        <div class="config-panel">
            <div class="section" style="animation-delay: 0.1s;">
                <!-- 车型 -->
                <h2 class="section-title">选择车型</h2>

                <div class="option-grid">
                    <div th:each="m : ${models}" class="option-card"
                         th:data-name="${m.model_name}"
                         th:data-price="${m.base_price}"
                         data-type="model">
<!--                        <img th:src="${m.modelImg}" width="100%" height="120" style="object-fit:cover;border-radius:6px"/>-->
                        <div class="option-name" th:text="${m.model_name}"></div>
                        <div class="option-price" th:text="'¥' + ${#numbers.formatDecimal(m.base_price,1,0)}"></div>
                    </div>
                </div>

            </div>

            <div class="section" style="animation-delay: 0.2s;">
                <h2 class="section-title">选择颜色</h2>

                <!-- 颜色 -->
                <div class="color-options">
                    <div th:each="c : ${colors}"
                         class="color-option"
                         th:style="'background:'+ ${c.color_hex}"
                         th:title="${c.color_name}"
                         th:data-color="${c.color_name}"
                         th:data-price="${c.extra_price}">
<!--                        <img th:src="${c.colorImg}" style="width:100%;height:100%;object-fit:cover;border-radius:50%">-->
                    </div>
                </div>

            </div>

            <div class="section" style="animation-delay: 0.3s;">
                <h2 class="section-title">内饰选择</h2>

                <!-- 内饰 -->
                <div class="option-grid">
                    <div th:each="i : ${interiors}" class="option-card"
                         th:data-name="${i.interior_name}"
                         th:data-price="${i.extra_price}"
                         data-type="interior">
<!--                        <img th:src="${i.interiorImg}" width="100%" height="120" style="object-fit:cover;border-radius:6px"/>-->
                        <div class="option-name" th:text="${i.interior_name}"></div>
                        <div class="option-price" th:text="'¥' + ${#numbers.formatDecimal(i.extra_price,1,0)}"></div>
                    </div>
                </div>


            </div>

            <div class="section" style="animation-delay: 0.4s;">
                <h2 class="section-title">选装配置</h2>

                <!-- 选装配置 -->
                <div class="option-grid">
                    <div th:each="o : ${options}" class="option-card"
                         th:data-name="${o.option_name}"
                         th:data-price="${o.extra_price}"
                         data-type="option">
<!--                        <img th:src="${o.optionImg}" width="100%" height="120" style="object-fit:cover;border-radius:6px"/>-->
                        <div class="option-name" th:text="${o.option_name}"></div>
                        <div class="option-price" th:text="'¥' + ${#numbers.formatDecimal(o.extra_price,1,0)}"></div>
                        <div class="option-description" th:text="${o.description}"></div>
                    </div>
                </div>


            </div>
        </div>

        <div class="preview-panel">
            <div class="car-preview">
                <div class="car-image">
                    <img id="carImage" src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 400 250'%3E%3Crect width='400' height='250' fill='%23f0f0f0'/%3E%3Ctext x='200' y='125' text-anchor='middle' dy='.3em' font-family='Arial' font-size='20' fill='%23999'%3E汽车预览图%3C/text%3E%3C/svg%3E" alt="汽车预览">
<!--                    <img id="carImage" src="/uploads/a4_series.jpg" alt="汽车预览">-->
                </div>
                <h3 id="selectedModel">请选择车型</h3>
                <p id="selectedColor">请选择颜色</p>
            </div>

            <div class="summary">
                <h3>配置摘要</h3>
                <div id="summaryList" class="add_pdding">
                    <div class="summary-item">
                        <span>基础车型</span>
                        <span>¥0</span>
                    </div>
                </div>
                <div class="progress-bar">
                    <div class="progress-fill" id="progressFill"></div>
                </div>
                <div class="summary-total">
                    总价：<span id="totalPrice">¥0</span>
                </div>
                <div style="text-align: center; margin-top: 20px;">
                    <button class="btn" onclick="resetConfig()">重置配置</button>
                    <button class="btn btn-primary" onclick="submitOrder()">提交订单</button>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="loading" id="loading">处理中...</div>


<script th:inline="javascript">
    let selectedConfig = {
        model: null,
        color: { name: null, price: 0 },
        interior: null,
        options: []
    };
    window.maxPrice = /*[[${maxPrice}]]*/ 0;
    let basePrice = 0;

    // 初始化
    document.addEventListener('DOMContentLoaded', function() {
        setupEventListeners();
        updateSummary();
    });

    function setupEventListeners() {
        // 车型选择
        document.querySelectorAll('[data-type="model"]').forEach(card => {
            card.addEventListener('click', function() {
                document.querySelectorAll('[data-type="model"]').forEach(c => c.classList.remove('selected'));
                this.classList.add('selected');
                selectedConfig.model = {
                    name: this.dataset.name,
                    price: parseInt(this.dataset.price)
                };
                basePrice = parseInt(this.dataset.price);
                document.getElementById('selectedModel').textContent = this.dataset.name;
                updateCarImage();
                updateSummary();
            });
        });

        // 颜色选择 .color-option'
        document.querySelectorAll('.color-option').forEach(option => {
            option.addEventListener('click', function() {
                document.querySelectorAll('.color-option').forEach(o => o.classList.remove('selected'));
                this.classList.add('selected');
                selectedConfig.color = {
                    name: this.dataset.color,
                    price: parseInt(this.dataset.price)
                };
                document.getElementById('selectedColor').textContent = `颜色：${this.dataset.color}`;
                updateCarImage();
                updateSummary();
            });
        });

        // 内饰选择
        document.querySelectorAll('[data-type="interior"]').forEach(card => {
            card.addEventListener('click', function() {
                document.querySelectorAll('[data-type="interior"]').forEach(c => c.classList.remove('selected'));
                this.classList.add('selected');
                selectedConfig.interior = {
                    name: this.dataset.name,
                    price: parseInt(this.dataset.price)
                };
                updateSummary();
            });
        });

        // 选装配置
        document.querySelectorAll('[data-type="option"]').forEach(card => {
            card.addEventListener('click', function() {
                this.classList.toggle('selected');
                const option = {
                    name: this.dataset.name,
                    price: parseInt(this.dataset.price)
                };

                if (this.classList.contains('selected')) {
                    selectedConfig.options.push(option);
                } else {
                    selectedConfig.options = selectedConfig.options.filter(opt => opt.name !== option.name);
                }
                updateSummary();
            });
        });
    }


    function updateCarImage() {
        const carImage = document.getElementById('carImage');

        // 如果车型或颜色还没选，显示默认占位图
        if (!selectedConfig.model || !selectedConfig.color.name) {
            carImage.src = 'data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 400 250\'%3E%3Crect width=\'400\' height=\'250\' fill=\'%23f0f0f0\'/%3E%3Ctext x=\'200\' y=\'125\' text-anchor=\'middle\' dy=\'.3em\' font-family=\'Arial\' font-size=\'20\' fill=\'%23999\'%3E汽车预览图%3C/text%3E%3C/svg%3E';
            return;
        }

        // 把中文颜色名映射成文件名里的英文
        const colorMap = {
            '曜石黑': 'black',
            '冰川白': 'white',
            '探戈红': 'red',
            '星际蓝': 'blue',
            '鎏金橙': 'orange',
            '天云灰':'gray'
        };
        const modelMap = {
            'A4 豪华版': 'a4',
            'A4 尊贵版': 'a4',
            'A6 豪华版': 'a6',
            'A6 旗舰版': 'a6',
        };

        const colorCode = colorMap[selectedConfig.color.name] || 'black';
        const modelCode = modelMap[selectedConfig.model.name]
        // 构造图片地址：/img/car/{车型}_{颜色}.png
        const imgSrc = `/uploads/${modelCode}_${colorCode}.png`;

        // 处理缓存：加时间戳防止浏览器缓存
        carImage.src = `${imgSrc}?t=${Date.now()}`;
    }
    // function updateCarImage() {
    //     const carImage = document.getElementById('carImage');
    //     const colors = {
    //         '黑色': '#000000',
    //         '白色': '#ffffff',
    //         '红色': '#e74c3c',
    //         '蓝色': '#3498db',
    //         '橙色': '#f39c12'
    //     };
    //
    //     const color = colors[selectedConfig.color.name] || '#000000';
    //     carImage.style.background = `linear-gradient(135deg, ${color}, ${color}88)`;
    // }


    function updateSummary() {
        const summaryList = document.getElementById('summaryList');
        const totalPrice  = document.getElementById('totalPrice');
        const progressFill= document.getElementById('progressFill');
        // var lastHeight = 0;

        // summaryList.innerHTML = '';
        // let total = 0;
        // let completedSteps = 0;
        // const totalSteps = 4;

        /* 1️⃣ 计算新条目列表 */
        const list = [
            selectedConfig.model ? { name: selectedConfig.model.name, price: selectedConfig.model.price } : null,
            selectedConfig.color.name && { name: `颜色：${selectedConfig.color.name}`, price: selectedConfig.color.price },
            selectedConfig.interior && { name: `内饰：${selectedConfig.interior.name}`, price: selectedConfig.interior.price },
            ...selectedConfig.options.map(o => ({ name: o.name, price: o.price }))
        ].filter(Boolean);

        /* 2️⃣ 条数不变 → 直接更新，不触发动画 */
        if (summaryList.children.length === list.length) {
            summaryList.innerHTML = '';
            list.forEach(item => {
                const div = document.createElement('div');
                div.className = 'summary-item';
                div.innerHTML = `<span>${item.name}</span><span>¥${item.price.toLocaleString()}</span>`;
                summaryList.appendChild(div);
            });
        } else {
            /* 3️⃣ 条数变化 → 带动画 */
            summaryList.style.transition = 'max-height .45s ease';
            summaryList.style.maxHeight = summaryList.scrollHeight + 'px';
            setTimeout(() => {
                summaryList.innerHTML = '';
                list.forEach(item => {
                    const div = document.createElement('div');
                    div.className = 'summary-item';
                    div.innerHTML = `<span>${item.name}</span><span>¥${item.price.toLocaleString()}</span>`;
                    summaryList.appendChild(div);
                });
                summaryList.style.maxHeight = summaryList.scrollHeight + 'px';
                // lastHeight = summaryList.scrollHeight
            }, 450);
        }

        // /* 4️⃣ 更新进度 & 总价（始终执行） */
        const total = list.reduce((s, it) => s + it.price, 0);
        const completedSteps = [selectedConfig.model, selectedConfig.color.name, selectedConfig.interior, selectedConfig.options.length > 0]
            .filter(Boolean).length;
        // progressFill.style.width = `${(completedSteps / 4) * 100}%`;
        totalPrice.textContent = `¥${total.toLocaleString()}`;


        // 更新进度
        // const progress = (completedSteps / totalSteps) * 100;
        // progressFill.style.width = `${progress}%`;
        // 更新总价
        // totalPrice.textContent = `¥${total.toLocaleString()}`;

        // 根据总价动态设置进度条长度
        const barLength = Math.min((total / maxPrice) * 100, 100);
        progressFill.style.width = `${barLength}%`;

    }

    function removeSummaryItem(item) {
        item.classList.add('removing');           // 触发过渡
        setTimeout(() => item.remove(), 450);     // 动画完成后删除
    }


    function addSummaryItem(name, price) {
        const summaryList = document.getElementById('summaryList');
        const item = document.createElement('div');
        item.className = 'summary-item';
        item.innerHTML = `<span>${name}</span><span>¥${price.toLocaleString()}</span>`;

        /* 关键：先让浏览器计算高度，再清掉过渡锁 */
        summaryList.appendChild(item);
        item.style.transition = 'none';           // 先禁用过渡
        item.style.maxHeight  = item.scrollHeight + 'px';
        item.style.marginBottom = '10px';
        item.style.opacity = '1';
        setTimeout(() => item.style.transition = 'all .45s ease', 0); // 再启用过渡
    }


    function resetConfig() {
        selectedConfig = {
            model: null,
            color: { name: null, price: 0 },
            interior: null,
            options: []
        };

        document.querySelectorAll('.option-card').forEach(card => {
            card.classList.remove('selected');
        });

        document.querySelectorAll('.color-option').forEach(option => {
            option.classList.remove('selected');
        });

        document.querySelector('.color-option').classList.add('selected');

        document.getElementById('selectedModel').textContent = '请选择车型';
        // document.getElementById('selectedColor').textContent = '颜色：黑色';

        updateCarImage();
        updateSummary();
    }

    function submitOrder() {


        if (!selectedConfig.model) {
            alert('请先选择车型！');
            return;
        }

        const loading = document.getElementById('loading');
        // const seriesId = document.getElementById('seriesId').value;

        loading.style.display = 'block';

        setTimeout(() => {
            loading.style.display = 'none';

            const orderDetails = {
                seriesId: document.getElementById('ser  iesId').value,
                model: selectedConfig.model.name,
                color: selectedConfig.color.name,
                interior: selectedConfig.interior?.name || '标准内饰',
                options: selectedConfig.options.map(opt => opt.name),
                total: document.getElementById('totalPrice').textContent
            };
            alert(`订单提交成功！\n${JSON.stringify(orderDetails, null, 2)}`);
        }, 1500);

    }
</script>
</body>
</html>